<template>
  <div>
    <el-card style="margin: 20px 0">

    </el-card>
    <el-card>
      <div>
        <el-button type="primary" @click="addSpuAction" icon="el-icon-plus" style="margin: 0 0 10px 0">新增SPU
        </el-button>
        <el-table border="border" :data="tableData" style="width: 100%">
          <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="productName" label="Spu名称" width="250"></el-table-column>
          <el-table-column prop="productDesc" label="描述" width="600"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="150"></el-table-column>
          <el-table-column prop="createBy" label="创建人" width="100"></el-table-column>
          <el-table-column prop="prop" label="操作" width="280">
            <template slot-scope="{row,$index}">
              <el-button icon="el-icon-edit" @click="showDialogAction(row)" type="primary">编辑</el-button>
              <el-button icon="el-icon-s-promotion" @click="showAuthorizationDialogAction(row)" type="warning">授权
              </el-button>
              <el-button icon="el-icon-delete" type="danger" @click="delAction(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>


    <el-drawer
      title="我是标题"
      :visible.sync="drawer"
      :direction="direction"
      size="70%"
      :before-close="handleClose">
      <div style="padding: 0 40px 40px 40px">
        <el-form :model="form" ref="ruleForm" :rules="rules">

          <el-form-item label="模型名称" prop="modelId">
            <el-select v-model="form.modelId" @change="handleChangeModelAction" placeholder="请选择">
              <el-option
                v-for="item in allModels"
                :key="item.modelId"
                :label="item.modelName"
                :value="item.modelId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-button type="primary" :disabled="!form.modelId" icon="el-icon-plus" @click="addSpecAction"
                     style="margin: 0 0 10px 0">新增规格
          </el-button>
          <el-table border="border" :data="tableDataSpecList" style="width: 100%">
            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
            <el-table-column prop="specName" align="center" label="规格名称" width="150">

              <template slot-scope="{row,$index}">
                <el-input @blur="blurSpecAction(row,$index)" placeholder="请输入规格名称" v-model="row.specName"
                          autocomplete="off"></el-input>
              </template>

            </el-table-column>
            <el-table-column prop="specDesc" label="规格项">
              <!--            :ref="setRef($index)"-->

              <template slot-scope="{row,$index}">
                <el-tag closable style="margin-right: 10px"
                        v-for="(item, index) in row.specItemList"
                        @close="handleCloseSpecItemAction(item,$index)"
                        :key="item.specItemId">{{item.specItemName}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-show="row.inputVisible"
                  v-model="row.inputValue"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row,$index)"
                  @blur="handleInputConfirm(row,$index)"
                >
                </el-input>

                <el-button v-show="!row.inputVisible" class="button-new-tag" @click="showInput(row,$index)">+ 规格项
                </el-button>
              </template>

            </el-table-column>
            <el-table-column prop="prop" label="操作" align="center" width="100">
              <template slot-scope="{row,$index}">
                <el-button @click="delSpecAction(row,$index)" type="danger" icon="el-icon-delete"
                           circle></el-button>
              </template>
            </el-table-column>
          </el-table>


          <el-table
            :data="tableDataSkuList"
            border
            style="width: 100%;margin-top: 30px">
            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>

            <el-table-column
              prop='giftDarkImg'
              label="礼物灰图"
              width="180">
          <template slot-scope="{row,$index}">
                <el-upload action=""
                           :action="fileUpload"
                           :on-success="
                           (response, file,fileList) =>
                             handleSuccess(
                               response,
                               file,
                               fileList
                             )
                         "
                           :file-list="row.skuImageList" list-type="picture"  accept="image/*"  ref="img-Imggrey" :limit="1">
                  <el-button size="small" type="primary">点击选择图片</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
                </el-upload>
              </template>
            </el-table-column>


            <el-table-column
              prop="address"
              align="center"
              label="规格">

              <template slot-scope="{row,$index}">
              <span v-for="(item, index1) in row.specList" :key="item.specId">
                <span style="margin-right: 10px;"
                      v-for="(item2, index2) in item.specItemList"
                      :key="item2.specItemId">
                  <span style="font-size: 15px;font-weight: bold;">{{item.specName}}</span>
                     <span style="font-size: 14px">{{ "："+item2.specItemName}}</span>
                  <!--                     <span style="font-size: 14px">{{ "："+item2.specItemId}}</span>-->

                </span>
              </span>
              </template>


            </el-table-column>


            <el-table-column
              prop="skuStock"
              label="库存"
              align="center"
              width="120">
              <template slot-scope="{row,$index}">
                <el-input-number v-model="row.skuStock" style="width: 100%" @change="handleChange" :min="1" :max="10000"
                                 label="描述文字"></el-input-number>
              </template>
            </el-table-column>

            <el-table-column
              prop="skuCode"
              label="SKU编码"
              align="center"
              width="200">
              <template slot-scope="{row,$index}">
                <el-input style="width: 100%;height: 100%" :maxlength="50" v-model="row.skuCode"
                          prop="skuCode"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              prop="skuPrice"
              width="110"
              align="center"
              label="价格(元)">
              <template slot-scope="{row,$index}">
                <el-input style="width: 100%;height: 100%" :minLength="1" :maxlength="10" v-model="row.skuPrice"
                          prop="skuPrice"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              prop="skuIfHidden"
              label="启用/禁用"
              align="center"
              width="200">

              <template slot-scope="{row,$index}">
                <el-switch
                  style="display: block;width: 100%;height: 100%"
                  active-color="#13ce66"
                  v-model="row.skuIfHidden"
                  inactive-color="#ff4949"
                  active-text="启用"
                  @change="handleSwitchChange"
                  inactive-text="禁用">
                </el-switch>
              </template>

            </el-table-column>

          </el-table>
        </el-form>
        <div class="drawer-footer">
          <el-button @click="cancelAction('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="addAction">确 定</el-button>
        </div>
      </div>

    </el-drawer>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
  import * as api from './api'

  export default {
    name: "spu",
    data() {
      return {
        title: "新增",
        pageDto: {
          pageNum: 1,
          pageSize: 10,
        },
        pageDto2: {
          pageNum: 1,
          pageSize: 10,
        },
        total: 0,
        tableData: [],

        dialogImageUrl: '',
        dialogVisible: false,

        // 规格数组
        tableDataSpecList: [],
        tableDataSkuList: [],
        allModels: [],
        drawer: false,
        direction: 'rtl',
        form: {
          modelId: null,

        },
        rules: {
          modelId: [
            {required: true, message: '请选择模型', trigger: 'blur'},
          ],
        },
        fileList: []
      }

    },
    mounted() {
      // 组件加载完毕发出请求
      this.pageAction();
      // this.specAction();
      api.modelListRequest().then((res) => {
        this.allModels = res.data;
      });
    },
    methods: {
      //加载分页
      async pageAction() {
        let result = await api.pageRequest(this.pageDto)
        this.tableData = result.data.list;
        this.total = result.data.total;
      },
      handleChangeModelAction(value) {
        this.modelId = value;
        //刷新规格
        api.specListByModelId(this.modelId).then((res) => {
          this.tableDataSpecList = res.data;
          for (let i = 0; i < this.tableDataSpecList.length; i++) {
            this.tableDataSpecList[i].inputVisible = false;
          }
        });
        // 刷新sku
        api.convertSkuByModelId(this.modelId).then((res) => {
          this.tableDataSkuList = res.data;
        })

      },

      blurSpecAction(row, index) {
        //编辑规格
        row.modelId = this.modelId
        api.updateSpecNameByIdRequest(row).then(res => {

          api.specListByModelId(this.modelId).then((res) => {
            this.tableDataSpecList = res.data;
            for (let i = 0; i < this.tableDataSpecList.length; i++) {
              this.tableDataSpecList[i].inputVisible = false;
            }
          });


          // 刷新sku
          api.convertSkuByModelId(this.modelId).then((res) => {
            this.tableDataSkuList = res.data;
          })
        })

      },


      // async specAction() {
      //   let result = await api.specRequest(this.pageDto2)
      //   this.tableDataSpecList = result.data.list;
      //   for (let i = 0; i < this.tableDataSpecList.length; i++) {
      //     this.tableDataSpecList[i].inputVisible = false;
      //   }
      // },
      async addSpuAction() {
        this.drawer = true
        // let result = await api.skuList3(this.pageDto)
        // this.tableDataSkuList = result.data;
      },

      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
      },
      //新增规格
      addSpecAction() {
        let item = {
          specId: null,
          specName: "",
          specItemList: []
        }
        this.tableDataSpecList.push(item);
      },
      //删除规格/规格项
      delSpecAction(row, index) {
        this.tableDataSpecList.splice(index, 1);
        if (row.specId) {
          api.delRequest(row.specId).then(res => {
            // 刷新sku
            api.convertSkuByModelId(this.modelId).then((res) => {
              this.tableDataSkuList = res.data;
            })
          })
        }


      },
      //删除规格项
      handleCloseSpecItemAction(tag, index) {
        this.tableDataSpecList[index].specItemList.splice(this.tableDataSpecList[index].specItemList.indexOf(tag), 1);
        api.delSpecItemById(tag.specItemId).then(res => {
          // 刷新sku
          api.convertSkuByModelId(this.modelId).then((res) => {
            this.tableDataSkuList = res.data;
          })
        })
      },

      // 新增规格项目 这一行row
      showInput(row, index) {
        row.inputVisible = true;
        this.tableDataSpecList[index].specItemList.push(row)
        this.tableDataSpecList[index].specItemList.splice(this.tableDataSpecList[index].specItemList.indexOf(row), 1);
        // this.$nextTick(_ => {
        //   this.$refs["saveTagInput-"+index].$refs.input.focus();
        // });
      },
      handleInputConfirm(row, index) {
        let inputValue = row.inputValue;
        let specItem = {
          "specItemName": inputValue,
          "specId": row.specId
        }
        if (inputValue) {
          this.$set(this.tableDataSpecList[index].specItemList, this.tableDataSpecList[index].specItemList.length, specItem);
          row.inputVisible = false;
          row.inputValue = '';
        }

        api.specItemAddRequest(specItem).then(res => {
          //刷新规格
          api.specListByModelId(this.modelId).then((res) => {
            this.tableDataSpecList = res.data;
            for (let i = 0; i < this.tableDataSpecList.length; i++) {
              this.tableDataSpecList[i].inputVisible = false;
            }
          });
          // 刷新sku
          api.convertSkuByModelId(this.modelId).then((res) => {
            this.tableDataSkuList = res.data;
          })
        })
      },
      handleSwitchChange(value) {
        console.log(value);
      },
      handleChange(value) {
        console.log(value);
      },
      handleSuccess(response, file, fileList) {
        // 假设返回的response中包含了图片的url
        response.data.url = this.filePrefix + response.data.url
        this.tableDataSkuList[index].skuImageList.push(response.data)
      },
      handleRemove(file, fileList) {
        // this.tableDataSkuList[index].imageUrl = null; // 移除图片时，清空图片url
      },

      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },


      cancelAction() {
        this.$refs.ruleForm.resetFields();
        this.form.specItemList = [];
        this.dialogFormVisible = false
        // this.resetForm()
      },
      addAction() {
        this.form.tableDataSkuList = this.tableDataSkuList
        console.log(this.form)
        // <el-form :model="form"  ref="ruleForm"  :rules="rules">
        // this.$refs.ruleForm.validate((valid) => {
        //   if (valid) {
        //     //请求接口
        //
        //     api.addRequest(this.form).then(res => {
        //       if (200 === res.code) {
        //         //关闭弹窗
        //         this.dialogFormVisible = false
        //         //弹出提示
        //         this.$message({
        //           // message: res.msg,
        //           message: this.form.id === null ? '新增成功' : '编辑成功',
        //           type: 'success'
        //         });
        //         //刷新页面
        //         this.pageAction();
        //         //清空form表单
        //         this.resetForm()
        //       }
        //     })
        //   } else {
        //     console.log('error submit!!');
        //     return false;
        //   }
        // });
      },
    }
  }
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    /*margin-left: 10px;*/
    /*height: 32px;*/
    /*line-height: 30px;*/
    /*padding-top: 0;*/
    /*padding-bottom: 0;*/
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }


  /*sku图片*/
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }

  .avatar {
    width: 50px;
    height: 50px;
    display: block;
  }
</style>
